﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using System.Text;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class MieCarte : PhoneApplicationPage
    {
        private static string key = "user";

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private Style containerStyle = Application.Current.Resources["MyCardCanvas"] as Style;
        private Style borderStyle = Application.Current.Resources["MyCardCardBorder"] as Style;
        private Style nameTextStyle = Application.Current.Resources["MyCardTextName"] as Style;
        private Style topTextStyle = Application.Current.Resources["MyCardTextTOP"] as Style;
        private Style bottomTextStyle = Application.Current.Resources["MyCardTextBOT"] as Style;
        private Style leftTextStyle = Application.Current.Resources["MyCardTextLEFT"] as Style;
        private Style rightTextStyle = Application.Current.Resources["MyCardTextRIGHT"] as Style;
        private Style levelTextStyle = Application.Current.Resources["MyCardTextLEVEL"] as Style;
        private Style priceTextStyle = Application.Current.Resources["MyCardTextPrice"] as Style;
        //private Style rarityTextStyle = Application.Current.Resources["MyCardTextRARITY"] as Style;

        public MieCarte()
        {
            InitializeComponent();

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/myCards.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        private void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingMyCards(result));
            }
        }//GetResponsetStreamCallback

        private void ParsingMyCards(string result)
        {
            //controllo result
            if (result != "")//ho preferiti
            {
                //parsing e creo lista
                string[] ris = majorSplit(result);
                foreach (string record in ris)
                {
                    string[] dati = minorSplit(record);
                    string name = dati[2];
                    string imageURL = dati[1];
                    string top = dati[3];
                    string bottom = dati[4];
                    string left = dati[5];
                    string right = dati[6];
                    string cost = dati[8];
                    string level = dati[7];

                    Canvas container = new Canvas();
                    container.Style = containerStyle;
                    var containerback = new ImageBrush();
                    Uri imageuricontainer = new Uri("img/buttonbg.png", UriKind.Relative);
                    containerback.ImageSource = new BitmapImage(imageuricontainer);
                    container.Background = containerback;

                    Border bord = new Border();
                    bord.Style = borderStyle;
                    var bordback = new ImageBrush();
                    Uri imageuribord = new Uri(imageURL, UriKind.Relative);
                    bordback.ImageSource = new BitmapImage(imageuribord);
                    bord.Background = bordback;

                    TextBlock nameText = new TextBlock();
                    nameText.Style = nameTextStyle;
                    nameText.Foreground = new SolidColorBrush(Colors.Black);
                    nameText.Text = name;

                    TextBlock topText = new TextBlock();
                    topText.Style = topTextStyle;
                    topText.Foreground = new SolidColorBrush(Colors.Black);
                    topText.Text = top;

                    TextBlock bottomText = new TextBlock();
                    bottomText.Style = bottomTextStyle;
                    bottomText.Foreground = new SolidColorBrush(Colors.Black);
                    bottomText.Text = bottom;

                    TextBlock leftText = new TextBlock();
                    leftText.Style = leftTextStyle;
                    leftText.Foreground = new SolidColorBrush(Colors.Black);
                    leftText.Text = left;

                    TextBlock rightText = new TextBlock();
                    rightText.Style = rightTextStyle;
                    rightText.Foreground = new SolidColorBrush(Colors.Black);
                    rightText.Text = right;

                    /*TextBlock priceText = new TextBlock();
                    priceText.Style = priceTextStyle;
                    priceText.Foreground = new SolidColorBrush(Colors.Black);
                    priceText.Text = cost;*/

                    TextBlock levelText = new TextBlock();
                    levelText.Style = levelTextStyle;
                    levelText.Foreground = new SolidColorBrush(Colors.Black);
                    levelText.Text = "Level:\n" + level;

                    /*TextBlock rarityText = new TextBlock();
                    rarityText.Style = rarityTextStyle;
                    rarityText.Foreground = new SolidColorBrush(Colors.Black);
                    rarityText.Text = "Rarity" + rarity;*/

                    container.Children.Add(bord);
                    container.Children.Add(nameText);
                    container.Children.Add(topText);
                    container.Children.Add(bottomText);
                    container.Children.Add(leftText);
                    container.Children.Add(rightText);
                    /*container.Children.Add(priceText);*/
                    container.Children.Add(levelText);
                    //container.Children.Add(rarityText);

                    ContainerList.Items.Add(container);

                }
            }
        }

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}